package redis

import (
	"cart_srv/cartsrv"
	"context"
	"fmt"
	"strconv"
)

// AddCart 添加购物车
func AddCart(userId, goodsId, num int, name, cover string, price float64) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return Rdb.HMSet(context.Background(), key, map[string]interface{}{
		"goodsId":    goodsId,
		"goodsName":  name,
		"goodsCover": cover,
		"goodsPrice": price,
		"goodsNum":   num,
		"checked":    1,
	}).Err()
}

// FindCart 购物车查询
func FindCart(userId, goodsId int) int64 {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return Rdb.Exists(context.Background(), key).Val()
}

// UpdateCart 购物车商品数量增加
func UpdateCart(userId, goodsId, num int) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	val, _ := Rdb.HGetAll(context.Background(), key).Result()
	s, _ := strconv.Atoi(val["goodsNum"])
	nums := s + num
	return Rdb.HMSet(context.Background(), key, map[string]interface{}{
		"goodsNum": nums,
	}).Err()
}

// ListCart 购物车列表
func ListCart(userId int) (listCart []*cartsrv.ListCart, err error) {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_*", userId)
	keys, _ := Rdb.Keys(context.Background(), key).Result()
	fmt.Println("w ", keys)
	for _, k := range keys {

		val, _ := Rdb.HGetAll(context.Background(), k).Result()
		goodsId, _ := strconv.Atoi(val["goodsId"])
		name := val["goodsName"]
		cover := val["goodsCover"]
		price, _ := strconv.ParseFloat(val["goodsId"], 64)
		num, _ := strconv.Atoi(val["goodsId"])
		checked, _ := strconv.Atoi(val["goodsId"])

		listCart = append(listCart, &cartsrv.ListCart{
			GoodsId: int64(goodsId),
			Name:    name,
			Cover:   cover,
			Price:   float32(price),
			Num:     int64(num),
			Checked: int64(checked),
		})
		fmt.Println("我是list", listCart)
	}
	return
}
